﻿using SqlSugar;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFileView.Core.Repository
{

    public static class SqlSugarExtension
    {
        private static readonly ConcurrentDictionary<string, SqlFilterItem> filters = new ConcurrentDictionary<string, SqlFilterItem>();

        ///// <summary>
        ///// 动态增加过滤器
        ///// </summary>
        ///// <typeparam name="TEntity"></typeparam>
        ///// <param name="sqlSugarClient"></param>
        ///// <returns></returns>
        public static ISugarQueryable<TEntity> QueryFilter<TEntity>(this ISqlSugarClient sqlSugarClient) where TEntity : class, new()
        {
            //每次先清理过滤器
            sqlSugarClient.QueryFilter.Clear();
            string key = typeof(TEntity).FullName!;
            var filter = filters.GetOrAdd(key, x =>
            {
                if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
                {
                    string name = nameof(ISoftDelete.DeleteMark);
                    var item = new SqlFilterItem
                    {
                        FilterValue = filter => new SqlFilterResult { Sql = $" {name}=0" },
                        IsJoinQuery = false
                    };
                    return item;
                }
                return null;
            });
            if (filter != null)
            {
                sqlSugarClient.QueryFilter.Add(filter);
            }
            return sqlSugarClient.Queryable<TEntity>();
        }
        //public async static Task<List<T>> QueryableToTree<T>(this ISugarQueryable<T> queryable, Expression<Func<T, IEnumerable<object>>> func, Expression<Func<T, object>> func2, object val)
        //    => await queryable.ToTreeAsync(func, func2, 0);

        //public static ISugarQueryable<T> QueryableWhere<T>(this ISugarQueryable<T> queryable, Expression<Func<T, bool>> func)
        //=> queryable.Where(func);

    }
    public class ISoftDelete
    {
        public string? DeleteMark { get; set; }
    }
}
